<?php
/**
 * Last Changed:			$LastChangedDate$
 * @author					$Author$
 * @version					$Revision$
 * @package					Joomla.Site
 * @subpackage				com_bpshoppingcart
 * @copyright				Copyright (C) 2012 Binary Pursuits All Rights Reserved
 * @license					GNU General Public License version 3 or later; see LICENSE.txt
 */

// No direct access.
defined('_JEXEC') or die;

JLoader::register('BPShoppingCartModelProduct', JURI::base() . 'administrator/components/com_bpshoppingcart/models/product.php');

/**
 * Binary Pursuits Shooping Cart Component model.
 *
 * @package		Joomla.Site
 * @subpackage	com_bpshoppingcart
 */
class BPShoppingCartModelForm extends BPShoppingCartModelProduct
{
	
	/**
	 * 
	 * Method to add or update the product mapping table
	 * If the row already exists, update the start and end date.
	 * If the row doesn't exist, add a new row.
	 * 
	 * @param JObject $product	Product object 
	 * @param JUser $user User object
	 * @return	Boolean	true on success, false on failure
	 */
	public function updateProductMapping($product, $user)
	{
		// Check that we have valid inputs
		if (((int) $product->id) && ((int) $product->duration )
				&& ((int) $user->id)) {
			
			$today = JFactory::getDate()->toMySQL();
			$endDate = JFactory::getDate('+ ' . (int) $product->duration . ' days')->toMySQL();
			
			// Check whether the row exists 
			$mapRow = $this->getMapRow($product->id, $user->id);
			if ($mapRow === false) {
				// We have a database error
				return false;
			} else if ($mapRow) {
				// The row already exists, so update it
				if (!$this->updateMapRow($product->id, $user->id, $today, $endDate)) {
					return false;
				}
			} else {
				// The row doesn't exist, so add a new map row
				if (!$this->addMapRow($product->id, $user->id, $today, $endDate)) {
					return false;
				}
			}
			
			// At this point, we have successfully updated the database
			return true;			
		}
	}	
	
	protected function addMapRow ($subID, $userID, $startDate, $endDate) 
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$query->insert($db->nameQuote('#__bpcart_sub_mapping'));
		$query->set('product_id = ' . (int) $subID);
		$query->set('user_id = ' . (int) $userID);
		$query->set('start_date = ' . $db->quote($startDate));
		$query->set('end_date = ' . $db->quote($endDate));
		$db->setQuery($query);
		if ($db->query()) {
			return true;
		} else {
			$this->setError(JText::_('COM_BPSHOPPINGCART_ADD_MAP_ROW_FAIL'));
			return false;
		}
	}
	
	protected function getMapRow($subID, $userID) 
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$query->select('product_id, user_id, start_date, end_date');
		$query->from($db->nameQuote('#__bpcart_sub_mapping'));
		$query->where('product_id = ' . (int) $subID);
		$query->where('user_id = ' . (int) $userID);
		$db->setQuery($query);
		$data = $db->loadObject();
		if ($db->getErrorNum()) {
			$this->setError(JText::_('COM_BPSHOPPINGCART_GET_MAP_ROW_FAIL'));
			return false;
		} else {
			return $data;
		}
	}
	
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();

		// Load state from the request.
		$pk = JRequest::getInt('product_id');
		$this->setState('product.product_id', $pk);
		// Add compatibility variable for default naming conventions.
		$this->setState('form.id', $pk);

		$return = JRequest::getVar('return', null, 'default', 'base64');

		if (!JUri::isInternal(base64_decode($return))) {
			$return = null;
		}

		$this->setState('return_page', base64_decode($return));

		// Load the parameters.
		$params	= $app->getParams();
		$this->setState('params', $params);
		$this->setState('layout', JRequest::getCmd('layout'));
	}
	
	protected function updateMapRow($subID, $userID, $startDate, $endDate)
	{
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		$query->update($db->nameQuote('#__bpcart_sub_mapping'));
		$query->set('start_date = ' . $db->quote($startDate));
		$query->set('end_date = ' . $db->quote($endDate));
		$query->where('product_id = ' . (int) $subID);
		$query->where('user_id = ' . (int) $userID);
		$db->setQuery($query);
		if ($db->query()) {
			return true;
		} else {
			$this->setError(JText::_('COM_BPSHOPPINGCART_UPDATE_MAP_ROW_FAIL'));
			return false;
		}
	}
		
}
